/*
 * @Descripttion: OSS文件上传相关接口
 * @Author: Cascade
 * @Date: 2025-07-07
 * @LastEditTime: 2025-07-07 11:20:00
 * @LastEditors: sueRimn
 */

import { BASEHOST } from '../../config'
import Request from '../http'

/**
 * 获取OSS上传策略
 * @returns {Promise} OSS策略配置
 */
export const getOssPolicy = () => Request.get(`${BASEHOST}/api/oss/policy`, {})

/**
 * 执行上传文件到OSS
 * @param {Object} options 上传参数
 * @param {String} options.url OSS上传地址
 * @param {Object} options.formData 表单数据
 * @param {File|Object} options.file 文件对象
 * @param {Function} options.onProgress 进度回调
 * @returns {Promise} 上传结果
 */
export const executeOssUpload = ({ url, formData, file, onProgress }) => {
  return new Promise((resolve, reject) => {
    // 微信小程序环境下使用 uni.uploadFile
    if (typeof uni !== 'undefined') {
      const uploadTask = uni.uploadFile({
        url: url,
        filePath: file.path || file.tempFilePath,
        name: 'file',
        formData: formData,
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            const fileUrl = url + '/' + formData.key;
            resolve({
              success: true,
              url: fileUrl,
              key: formData.key
            });
          } else {
            reject(new Error(`上传失败: ${uploadRes.statusCode}`));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
      
      // 监听上传进度
      if (onProgress && uploadTask.onProgressUpdate) {
        uploadTask.onProgressUpdate((res) => {
          onProgress(res.progress);
        });
      }
    } else {
      // 浏览器环境下的上传实现
      const xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      
      // 监听上传进度
      if (onProgress) {
        xhr.upload.onprogress = (e) => {
          if (e.lengthComputable) {
            const percent = Math.floor((e.loaded / e.total) * 100);
            onProgress(percent);
          }
        };
      }
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          const fileUrl = url + '/' + formData.key;
          resolve({
            success: true,
            url: fileUrl,
            key: formData.key
          });
        } else {
          reject(new Error(`上传失败: ${xhr.status}`));
        }
      };
      
      xhr.onerror = () => {
        reject(new Error('网络错误'));
      };
      
      const formDataObj = new FormData();
      for (const key in formData) {
        formDataObj.append(key, formData[key]);
      }
      formDataObj.append('file', file);
      
      xhr.send(formDataObj);
    }
  });
}
